
const scpClient = require('scp2')
// import scpClient from 'scp2'
const ora = require('ora')
const chalk = require('chalk')
// import chalk from 'chalk'
// const server = require('./products');
const args = process.argv.slice(2) // 移除前两个参数（node 和脚本路径）

// 查找环境参数
const envArg = args.find(arg => arg.startsWith('--env='))
const env = envArg ? envArg.split('=')[1] : 'testing'// 默认环境为 development
let path = ''
console.log('env=', env)
switch (env) {
  case 'production':
    // 生产环境的部署逻辑
    path = '/data/yll/yll-non-custody-personnel-mansys-vue-prod-business-screen'
    console.log('Deploying to production...')
    break
  case 'testing':
    // 测试环境的部署逻辑
    path = '/data/yll/yll-non-custody-personnel-mansys-vue-test-business-screen'
    console.log('Deploying to testing...')
    break
  default:
    // 默认环境的部署逻辑
    path = '/data/yll/yll-non-custody-personnel-mansys-vue-test-business-screen'
    console.log('Deploying to development...')
}

const server = {
  username: 'root',
  password: 'NDqQn*AWEU%QNz!x',
  host: '36.7.128.202',
  port: '22',
  path: path // 非羁押测试环境
  // path: '/data/yll/yll-non-custody-personnel-mansys-vue-prod-business' // 非羁押生产环境
  // path: '/data/wxz/wxz-common-web-landlord-vue-test-base' // 个人用户

}
// const spinner = ora(
//   '正在发布到测试服务器...' +
//     (process.env.NODE_ENV === 'prod' ? '生产' : '测试') +
//     '服务器...'
// );
const spinner = ora(
  '正在发布到线上服务器...'
)

var Client = require('ssh2').Client

var conn = new Client()
conn
  .on('ready', function() {
    // rm 删除dist文件
    console.log(chalk.green('ssh连接成功！！！'))
    conn.exec(`rm -rf ${server.path}`, function(
      err,
      stream
    ) {
      if (err) throw err
      stream
        .on('close', function(code, signal) {
          // 在执行shell命令后，把开始上传部署项目代码放到这里面
          console.log(chalk.green('开始上传文件...'))
          spinner.start()
          scpClient.scp(
            './dist',
            {
              host: server.host,
              port: server.port,
              username: server.username,
              password: server.password,
              path: server.path
            },
            function(err) {
              spinner.stop()
              if (err) {
                console.log(chalk.red('发布失败.\n'))
                throw err
              } else {
                console.log(
                  chalk.green(
                    'Success! 成功发布到服务器上！'
                  )
                )
              }
            }
          )

          conn.end()
        })
        .on('data', function(data) {
          console.log('STDOUT: ' + data)
        })
        .stderr.on('data', function(data) {
          console.log('STDERR: ' + data)
        })
    })
  })
  .connect({
    host: server.host,
    port: server.port,
    username: server.username,
    password: server.password
    // privateKey: require('fs').readFileSync('/home/admin/.ssh/id_dsa')
  })
